class Snake {
    //蛇整体
    element: HTMLElement;
    //蛇头
    head: HTMLElement;
    //蛇身
    body: HTMLCollection;
    constructor() {
        this.element = document.getElementById('snake')!;
        this.head = document.getElementById('head')!;
        this.body = document.getElementById('snake')!.getElementsByTagName('div')!;
    }
    //获取蛇头坐标
    get X() {
        return this.head.offsetLeft;
    }
    get Y() {
        return this.head.offsetTop;
    }
    //增加身体长度
    addBody() {
        //在元素最后插入标签
        //innerHTML会中断程序，所以不能用
        this.element.insertAdjacentHTML("beforeend", "<div></div>");
    }
    //身体移动
    moveBody() {
        //将后边的一截移到前一截的位置
        //从后往前遍历
        for (let i = this.body.length - 1; i > 0; i--) {
            let X = (this.body[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.body[i - 1] as HTMLElement).offsetTop;
            (this.body[i] as HTMLElement).style.left = X + 'px';
            (this.body[i] as HTMLElement).style.top = Y + 'px';
        }
    }
    //设置蛇头坐标
    change(X: number, Y: number) {
        //检查是否撞墙
        if (X < 0 || X > 290 || Y < 0 || Y > 290) {
            throw new Error('蛇撞墙了');
        }
        this.moveBody();
        this.head.style.left = X + 'px';
        this.head.style.top = Y + 'px';
        this.checkHeadBody();
    }
    //检查蛇头是否撞上蛇身
    checkHeadBody() {
        for (let i = 3; i < this.body.length; i++) {
            let bd = this.body[i] as HTMLElement;
            if (this.X === bd.offsetLeft && this.Y === bd.offsetTop) {
                throw new Error('蛇吃了自己')
            }
        }
    }
}
export default Snake;